package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.utils.ScanText;
import com.heima.common.excpetion.CustException;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service("CommentRepayService")
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    GreenTextScan textScan;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ScanText scanText;

    @Autowired
    RedissonClient redisson;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        if (dto.getSize() == null || dto.getSize() == 0)
            dto.setSize(10);

        if (dto.getMinDate() == null)
            dto.setMinDate(new Date());
        // 获取评论回复列表
        List<ApCommentRepay> repayList = mongoTemplate.find(
                Query.query(Criteria.where("commentId").is(dto.getCommentId())
                        .and("createdTime").lt(dto.getMinDate())).limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC, "createdTime"))
                , ApCommentRepay.class
        );
        // 判断用户是否登录 否 ->直接返回评论列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null)
            return ResponseResult.okResult(repayList);

        ArrayList<ApCommentRepayVO> list = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : repayList) {
            // 根据评论Id和用户Id查询每个回复的点赞情况
            List<ApCommentRepayLike> likes = mongoTemplate.find(Query.query(Criteria
                    .where("commentRepayId").is(apCommentRepay.getId())
                    .and("authorId").is(user.getId())), ApCommentRepayLike.class);

            // 将每个回复信息封装成Vo
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);

            // 判断当前回复Id是否在点赞列表中
            for (ApCommentRepayLike like : likes) {
                if (like.getCommentRepayId().equals(apCommentRepay.getId())) {
                    apCommentRepayVO.setOperation((short) 0);
                    break;
                }
            }
            list.add(apCommentRepayVO);

        }


        return ResponseResult.okResult(list);
    }


    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {

        String content = dto.getContent();

        //将回复内容进行审核并进行敏感词替换
        content = scanText.scan(content);
        ApUser user = AppThreadLocalUtils.getUser();

        // 根据评论ID查询评论列表
        ApComment apComment = mongoTemplate.findOne(
                Query.query(Criteria.where("id").is(dto.getCommentId())
                        .and("authorId").is(user.getId())
                )
                , ApComment.class
        );

        //评论不存在
        if (apComment == null)
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);


        ApCommentRepay apCommentRepay = new ApCommentRepay();
        BeanUtils.copyProperties(apComment, apCommentRepay);
        apCommentRepay.setContent(content);
        apCommentRepay.setCommentId(apComment.getId());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);

        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);


        return ResponseResult.okResult();
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null)
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);

        RLock rLock = redisson.getLock("RepayLikes-lock");
        rLock.lock();

        HashMap<String, Object> hashMap;
        //执行回复点赞功能
        try {
            ApCommentRepay apCommentRepay = mongoTemplate.findOne(
                    Query.query(Criteria.where("commentId").is(dto.getCommentRepayId())
                            .and("authorId").is(user.getId())
                    )
                    , ApCommentRepay.class
            );
            //点赞的评论不存在
            if (apCommentRepay == null)
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);

            Short operation = dto.getOperation();
            hashMap = new HashMap<>(1);

            // 用户执行的点赞操作
            if (operation == 0) {
                ApCommentRepayLike repayLike = mongoTemplate.findOne(
                        Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId())
                                .and("authorId").is(user.getId())
                        )
                        , ApCommentRepayLike.class
                );
                // 用户已经点过赞
                if (repayLike != null)
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "已经点赞过,请勿重复点赞");
                else {
                    ApCommentRepayLike commentRepayLike = new ApCommentRepayLike();
                    BeanUtils.copyProperties(dto, commentRepayLike);
                    commentRepayLike.setAuthorId(user.getId());

                    mongoTemplate.save(commentRepayLike);

                    apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
                    mongoTemplate.save(apCommentRepay);
                    hashMap.put("likes", apCommentRepay.getLikes());

                }

            } else {
                // 用户执行的取消点赞操作 ->根据评论回复表Id和用户Id删除数据
                mongoTemplate.remove(Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId())
                                .and("authorId").is(user.getId()))
                        , ApCommentRepayLike.class);

                //减去点赞数
                apCommentRepay.setLikes(apCommentRepay.getLikes() - 1);
                mongoTemplate.save(apCommentRepay);
                hashMap.put("likes", apCommentRepay.getLikes());
            }
        } finally {
            rLock.unlock();
        }

        return ResponseResult.okResult(hashMap);
    }
}
